package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.adapter.HomeLeftMenuAdapter;
import com.wuliupai.delivery.wuliupaidelivery.adapter.TaskListAdapter;
import com.wuliupai.delivery.wuliupaidelivery.bean.MyInfoBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.UpdateBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.task.TaskBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.task.TaskListResult;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.CommConstants;
import com.wuliupai.delivery.wuliupaidelivery.constants.Flag;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.PageFlag;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.service.DownloadService;
import com.wuliupai.delivery.wuliupaidelivery.service.LocationService;
import com.wuliupai.delivery.wuliupaidelivery.ui.MyToolbar;
import com.wuliupai.delivery.wuliupaidelivery.utils.ActivityCollector;
import com.wuliupai.delivery.wuliupaidelivery.utils.CommonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.FileUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.SharePreferenceUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

import cn.bingoogolapple.refreshlayout.BGARefreshLayout;

/**
 * Descriptions：当前任务列表
 * <p>
 * Author：ChenME
 * Date：2016/11/15
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_task_current_list)
public class TaskCurrentListActivity extends AppBaseActivity implements BGARefreshLayout.BGARefreshLayoutDelegate, AppBaseActivity.OnRefreshBtnClickListener {

    @ViewById(R.id.toolbar)
    MyToolbar toolbar;
    @ViewById(R.id.drawerLayout)
    DrawerLayout drawerLayout;
    @ViewById(R.id.lv_leftMenu)
    ListView lv_leftMenu;//侧滑菜单列表
    @ViewById(R.id.btn_placeOrder)
    Button btn_placeOrder;

    @ViewById(R.id.refreshMyOrder)
    BGARefreshLayout refreshMyOrder;
    @ViewById(R.id.lv_myOrderList)
    RecyclerView lv_myOrderList;

    /**
     * 侧边栏
     */
    @ViewById(R.id.iv_myInfoPhoto)
    ImageView iv_myInfoPhoto;//头像
    @ViewById(R.id.tv_myInfoName)
    TextView tv_myInfoName;//姓名

    @ViewById(R.id.tv_versionName)
    TextView tv_versionName;

    private List<TaskBean> taskList;
    private TaskListAdapter adapter_order;
    private int startPosition;
    private MyInfoBean myInfoBeanParse;

    private ProgressDialog downloadProgressDialog;//下载进度提示对话框
    private AlertDialog updateDialog;//更新提示对话框

    private ActionBarDrawerToggle mDrawerToggle; //侧边栏开关
    private LocalBroadcastManager lbm;

    private TaskCurrentListActivity _activity;

    private BroadcastReceiver broadcastReceiverScan = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (null != action) {
                switch (action) {
                    case BroadcastChannels.Channel_DownloadApk: //下载APP
                        int progress = intent.getIntExtra("progress", 0);
                        try {
                            if (null != updateDialog) {
                                updateDialog.dismiss();
                            }
                            if (null == downloadProgressDialog) {
                                downloadProgressDialog = new ProgressDialog(TaskCurrentListActivity.this);
                                downloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                downloadProgressDialog.setCancelable(false);
                                downloadProgressDialog.show();
                                downloadProgressDialog.setMax(100);
                            }
                            downloadProgressDialog.setProgress(progress);
                            if (progress >= 98) {
                                downloadProgressDialog.dismiss();
                                downloadProgressDialog = null;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case BroadcastChannels.Channel_CreateOrderSuccessFully: // 下单成功
                    case BroadcastChannels.Channel_AcceptTaskSuccessWhenChangeTask: // 接收任务成功
                    case BroadcastChannels.Channel_GrabOrderSuccess: // 抢单成功
                    case BroadcastChannels.Channel_SignForSuccess: // 签收成功
                        getOrderList(true, null);//获取数据
                        break;


                }
            }
        }
    };

    @AfterViews
    void onPageStart() {
        _activity = this;
        registerBrodcastReceiver();
        checkUpdate();
        commitLocation();
        setTitle(this, R.string.string_title_my_order, R.mipmap.common_warn, true, new OnNavigationBtnClickListener() {
            @Override
            public void navigationClick() {
                finish();
                animUtils.leftOutAnimation(_activity);
            }

            @Override
            public void menuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menuItem1:
                        GrabOrderListActivity_.intent(_activity).start();
                        animUtils.leftInAnimation(_activity);
                        break;
                }
            }
        });
        // 设置侧边栏开关
        mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, 0, 0) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };

        mDrawerToggle.syncState();
        drawerLayout.setDrawerListener(mDrawerToggle);

        //设置菜单列表
        HomeLeftMenuAdapter adapter = new HomeLeftMenuAdapter(_activity);
        lv_leftMenu.setAdapter(adapter);
        lv_leftMenu.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onLeftMenuItemClick(position);
            }
        });

        //显示版本号
        tv_versionName.setText(String.format(getString(R.string.string_versionName), CommonUtils.getVersionName()[0]));

        bindOrderList();//绑定数据
        getUserInfo();
        setListener();

        getOrderList(true, null);//获取数据
    }

    /**
     * 左侧菜单栏的点击事件
     *
     * @param position
     */
    private void onLeftMenuItemClick(int position) {
        switch (position) {
            case 0://-订单记录
                TaskRecordListActivity_.intent(_activity).start();
                animUtils.leftInAnimation(_activity);
                break;
            case 1://-派哥钱包
                WalletActivity_.intent(this).start();
                animUtils.leftInAnimation(_activity);
                break;
            case 2://-计算运费
                CalculateFreightActivity_.intent(_activity)
                        .calculateAct(Flag.CALCULATE_NO_BACK)
                        .start();
                animUtils.leftInAnimation(_activity);
                break;
            case 3://-任务统计
                MissionStatisticsActivity_.intent(this).start();
                animUtils.leftInAnimation(_activity);
                break;
            case 4://-修改密码
                SetPasswordActivity_.intent(this).ifModification(Value.SetPasswordType_Modification).ifSetupTradingPassword(false).start();
                animUtils.leftInAnimation(_activity);
                break;
            case 5://-系统消息
                SystemMessageActivity_.intent(this).start();
                animUtils.leftInAnimation(_activity);
                break;
            case 6://-退出登录
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage(getString(R.string.string_setting_logout_tips));
                builder.setTitle("提示");
                builder.setPositiveButton("取消", (dialog, which) -> dialog.dismiss());

                builder.setNegativeButton("退出", (dialog, which) -> {
                    dialog.dismiss();
                    if (FileUtils.deleteFile(CommConstants.CACHE_DIR + CommConstants.TAG)) {
                        LoginActivity_.intent(_activity).start();
                        ActivityCollector.finishAll();
                    }
                });
                builder.create().show();
                break;
        }
        drawerLayout.closeDrawers();
    }

    /**
     * 绑定列表数据
     */
    private void bindOrderList() {
        taskList = new ArrayList<>();
        adapter_order = new TaskListAdapter(this, taskList, TaskListAdapter.Page_Current);
        refreshMyOrder.setDelegate(this);
        initRefreshView(_activity, refreshMyOrder, true, true);
        lv_myOrderList.setLayoutManager(new LinearLayoutManager(this));
        lv_myOrderList.setAdapter(adapter_order);
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        MyInfoBean myInfoBean = new MyInfoBean();
        String jsonMyInfo = JsonUtils.createJsonString(myInfoBean);
        try {
            String aesMyInfo = JsonUtils.aes(jsonMyInfo);
            callNet(_activity, InterfaceNet.Net_GetUserInfo, aesMyInfo, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (!StringUtils.isEmpty(content)) {
                        myInfoBeanParse = (MyInfoBean) JsonUtils.parseJsonString(content, MyInfoBean.class);
                        tv_myInfoName.setText(myInfoBeanParse.getName());
                        List<MyInfoBean> parseAreaList = myInfoBeanParse.infolist;
                        List<MyInfoBean> areaListSaves = new ArrayList<MyInfoBean>();
                        for (int i = 0; i < parseAreaList.size(); i++) {
                            MyInfoBean myInfoBeanParseList = new MyInfoBean();
                            myInfoBeanParseList.setProvinceCode(parseAreaList.get(i).getProvinceCode());
                            myInfoBeanParseList.setCityCode(parseAreaList.get(i).getCityCode());
                            myInfoBeanParseList.setAreaCode(parseAreaList.get(i).getAreaCode());
                            areaListSaves.add(myInfoBeanParseList);
                        }
                        String jsonAreaSave = JsonUtils.createJsonString(areaListSaves);
                        SharePreferenceUtil.saveMyInfo(_activity, myInfoBeanParse.getName(), jsonAreaSave, myInfoBeanParse.getPayPasswordStauts(), myInfoBeanParse.getBankStauts());
                    }
                }

                @Override
                public void onDataEmpty(String content) {

                }

                @Override
                public void onDataEnd(String content) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取订单列表
     */
    private void getOrderList(final boolean isClear, final BGARefreshLayout refreshLayout) {

        int si = startPosition;
        if (!isClear) {
            si += Value.listCount;
        }
        TaskBean taskBean = new TaskBean(String.valueOf(si), String.valueOf(Value.listCount), "1");
        String jsonRequest = JsonUtils.createJsonString(taskBean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_GetMissionList, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    setCommenActivtiyType(CommConstants.TYPE_HIDE, _activity);
                    if (isClear) {//刷新
                        if (null != refreshLayout) {
                            refreshLayout.endRefreshing();
                        }
                        if (!StringUtils.isEmpty(content)) {
                            taskList.clear();
                        }
                    } else if (null != refreshLayout) {//加载更多
                        startPosition += Value.listCount;
                        refreshLayout.endLoadingMore();
                    }

                    if (!StringUtils.isEmpty(content)) {
                        TaskListResult result = (TaskListResult) JsonUtils.parseJsonString(content, TaskListResult.class);
                        taskList.addAll(result.getInfolist());
                        adapter_order.notifyDataSetChanged();
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                    setCommenActivtiyType(CommConstants.TYPE_EMPTY, _activity);
                    taskList.clear();
                    adapter_order.notifyDataSetChanged();
                    if (isClear) {
                        taskList.clear();
                        if (null != refreshLayout) {
                            refreshLayout.endRefreshing();
                        }
                    }
                    if (null != refreshLayout) {
                        refreshLayout.endLoadingMore();
                    }
                }

                @Override
                public void onDataEnd(String content) {
                    App.toast(R.string.strings_common_dateEnd);
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    setCommenActivtiyType(CommConstants.TYPE_ERROR, _activity);
                    super.onErr(errorCode, errorMsg, mContext);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * item的监听
     */
    private void setListener() {
        adapter_order.setOnItemClickListener(position -> {
            TaskDetailActivity_.intent(_activity).whichPage(PageFlag.Page_TaskCurrentList).taskId(taskList.get(position).getMissionId()).start();
            animUtils.leftInAnimation(_activity);
        });
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        startPosition = 0;
        getOrderList(true, refreshLayout);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        getOrderList(false, refreshLayout);
        return false;
    }

    @Click(R.id.iv_myInfoPhoto)
    void myInfo() {
        if (null == myInfoBeanParse) {
            App.toast("正在加载用户信息,请稍等...");
            return;
        }
        MyProfileActivity_.intent(_activity)
                .name(myInfoBeanParse.getName())
                .sex(myInfoBeanParse.getSex())
                .area(myInfoBeanParse.infolist)
                .driverNum(myInfoBeanParse.getDriverNum())
                .headUrl(myInfoBeanParse.getHeadUrl())
                .start();
        animUtils.leftInAnimation(_activity);
    }

    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menuItem1).setVisible(true).setTitle("抢单");
//        menu.findItem(R.id.menuItem1).setVisible(false);
        menu.findItem(R.id.menuItem2).setVisible(false);
        return true;
    }

    /**
     * 点击扫码
     */
    @Click(R.id.iBtn_scanQRCode)
    void iBtn_scanQRCodeClick() {
        ScanQRBarActivity_.intent(_activity).start();
        animUtils.leftInAnimation(_activity);
    }

    /**
     * 点击下单
     */
    @Click(R.id.btn_placeOrder)
    void placeAnOrder() {
        PlaceOrderActivityV2_.intent(this).fromWhichPage(Flag.ToPlaceOrder_FromCurrentMission).start();
        animUtils.leftInAnimation(this);
    }


    private void registerBrodcastReceiver() {
        lbm = LocalBroadcastManager.getInstance(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(BroadcastChannels.Channel_AcceptTaskSuccessWhenChangeTask);
        filter.addAction(BroadcastChannels.Channel_CreateOrderSuccessFully);
        filter.addAction(BroadcastChannels.Channel_GrabOrderSuccess);
        filter.addAction(BroadcastChannels.Channel_SignForSuccess);
        filter.addAction(BroadcastChannels.Channel_DownloadApk);
        lbm.registerReceiver(broadcastReceiverScan, filter);
    }

    @Override
    public void refreshClick() {
        getOrderList(false, null);
    }

    /**
     * 检查更新
     */
    private void checkUpdate() {
        UpdateBean requestBean = new UpdateBean();
        String requestJson = JsonUtils.createJsonString(requestBean);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            callNetWithoutProgressDialog(_activity, InterfaceNet.Net_CheckUpdate,
                    requestAes, new NetResultOperate() {
                        @Override
                        public void onSuccess(String content) {
                            if (!StringUtils.isEmpty(content)) {
                                Object obj = JsonUtils.parseJsonString(content, UpdateBean.class);
                                if (obj instanceof UpdateBean) {
                                    UpdateBean bean = (UpdateBean) obj;
                                    if ("1".equals(bean.getUpdate())) {
                                        //需要更新
                                        boolean isForce = "1".equals(bean.getMandatoryUpdate());
                                        AlertDialog.Builder updateBuilder = new AlertDialog.Builder(_activity);

                                        updateBuilder.setTitle("新版本提示")
                                                .setMessage(Html.fromHtml(bean.getDescription()))
                                                .setCancelable(false)
                                                .setPositiveButton("更新", (dialog, which) -> {
                                                    downloadApk(bean.getUpdateUrl(), isForce);
                                                    dialog.dismiss();
                                                    updateDialog = null;
                                                })
                                                .setNegativeButton("取消", (dialog, which) -> {
                                                    if (isForce) {
                                                        //强制更新
                                                        dialog.dismiss();
                                                        updateDialog = null;
                                                        ActivityCollector.finishAll();
                                                    } else {
                                                        dialog.dismiss();
                                                        updateDialog = null;
                                                    }
                                                });
                                        updateDialog = updateBuilder.create();
                                        updateDialog.show();
                                    }
                                }
                            }
                        }

                        @Override
                        public void onDataEmpty(String content) {
                        }

                        @Override
                        public void onDataEnd(String content) {
                        }

                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载Apk包
     */
    private void downloadApk(String url, boolean isSendBroadcast) {
        Intent intent = new Intent(this, DownloadService.class);
        intent.putExtra("downloadType", 1);
        intent.putExtra("downloadUrl", url);
        intent.putExtra("isSendBroadcast", isSendBroadcast);
        // 由intent启动service，后台运行下载进程，在服务中调用notifycation状态栏显示进度条
        startService(intent);
    }

    private void commitLocation() {
        Intent intent = new Intent(this, LocationService.class);
        startService(intent);
    }
}